package com.ruoyi.asms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.asms.domain.AsmsFaultResolveStage;
import com.ruoyi.asms.domain.FaultInfoView;
import com.ruoyi.asms.domain.dto.DelayResovleDto;
import com.ruoyi.asms.service.IAsmsAssetFullInfoService;
import com.ruoyi.asms.service.IAsmsFaultResolveStageService;
import com.ruoyi.asms.service.IFaultInfoViewService;
import com.ruoyi.common.core.domain.AsmsAssetFullInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.vo.ResolveOverTimeVo;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.security.annotation.PreAuthorize;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 故障处理阶段信息Controller
 * 
 * @author yfkj
 * @date 2021-10-21
 */
@RestController
@RequestMapping("/asms/AsmsFaultResolveStage")
public class AsmsFaultResolveStageController extends BaseController
{
    @Autowired
    private IAsmsFaultResolveStageService asmsFaultResolveStageService;
    @Autowired
    private IFaultInfoViewService faultInfoViewService;
    @Autowired
    private IAsmsAssetFullInfoService assetFullInfoService;

    /**
     * 查询故障处理阶段信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultResolveStage:list")
    @GetMapping("/list")
    public TableDataInfo list(AsmsFaultResolveStage asmsFaultResolveStage)
    {
        startPage();
        List<AsmsFaultResolveStage> list = asmsFaultResolveStageService.selectAsmsFaultResolveStageList(asmsFaultResolveStage);
        return getDataTable(list);
    }

    /**
     * 导出故障处理阶段信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultResolveStage:export")
    @Log(title = "故障处理阶段信息", businessType = BusinessType.EXPORT)
    @PostMapping(value="/export", produces = "application/octet-stream")
    public void export(HttpServletResponse response, AsmsFaultResolveStage asmsFaultResolveStage) throws IOException
    {
        List<AsmsFaultResolveStage> list = asmsFaultResolveStageService.selectAsmsFaultResolveStageList(asmsFaultResolveStage);
        ExcelUtil<AsmsFaultResolveStage> util = new ExcelUtil<AsmsFaultResolveStage>(AsmsFaultResolveStage.class);
        util.exportExcel(response, list, "故障处理阶段信息数据");
    }

    /**
     * 获取故障处理阶段信息详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultResolveStage:query")
    @GetMapping(value = "/{faultResolveStageId}")
    public AjaxResult getInfo(@PathVariable("faultResolveStageId") Long faultResolveStageId)
    {
        return AjaxResult.success(asmsFaultResolveStageService.selectAsmsFaultResolveStageByFaultResolveStageId(faultResolveStageId));
    }

    /**
     * 新增故障处理阶段信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultResolveStage:add")
    @Log(title = "故障处理阶段信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AsmsFaultResolveStage asmsFaultResolveStage)
    {
        return toAjax(asmsFaultResolveStageService.insertAsmsFaultResolveStage(asmsFaultResolveStage));
    }

    /**
     * 修改故障处理阶段信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultResolveStage:edit")
    @Log(title = "故障处理阶段信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AsmsFaultResolveStage asmsFaultResolveStage)
    {
        return toAjax(asmsFaultResolveStageService.updateAsmsFaultResolveStage(asmsFaultResolveStage));
    }

    /**
     * 删除故障处理阶段信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultResolveStage:remove")
    @Log(title = "故障处理阶段信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{faultResolveStageIds}")
    public AjaxResult remove(@PathVariable Long[] faultResolveStageIds)
    {
        return toAjax(asmsFaultResolveStageService.deleteAsmsFaultResolveStageByFaultResolveStageIds(faultResolveStageIds));
    }

    @GetMapping("/checkOvertimeResolves")
    public R<List<ResolveOverTimeVo>> checkOvertimeResolves(@RequestParam("overTime")Long overTime){
        List<ResolveOverTimeVo> vos =new ArrayList<>();
        List<AsmsFaultResolveStage> list = asmsFaultResolveStageService.list(new QueryWrapper<AsmsFaultResolveStage>()
                .eq(AsmsFaultResolveStage.STATUS, 0).lt(AsmsFaultResolveStage.START_TIME, System.currentTimeMillis() - overTime));
        for (AsmsFaultResolveStage item : list) {
            ResolveOverTimeVo vo = new ResolveOverTimeVo();
            BeanUtils.copyProperties(item, vo);
            vos.add(vo);
        }
        return R.ok(vos);
    }

    /**
     * 获取最新的10条故障处理记录
     * @return
     */
    @GetMapping("/getLatestFaultResovle")
    public R<List<AsmsFaultResolveStage>> getLatestFaultResovle() {
        //获取最新的10条故障处理记录
        List<AsmsFaultResolveStage> stageList = asmsFaultResolveStageService.list(new QueryWrapper<AsmsFaultResolveStage>()
                .select(AsmsFaultResolveStage.FAULT_RESOLVE_USER_ID, AsmsFaultResolveStage.END_TIME, AsmsFaultResolveStage.FAULT_ASSET_ID)
                .isNotNull(AsmsFaultResolveStage.END_TIME).orderByDesc(AsmsFaultResolveStage.FAULT_RESOLVE_STAGE_ID).last("limit 10")
        );

        //获取故障资产名称
        Set<Long> faultAssetIds = stageList.stream().map(AsmsFaultResolveStage::getFaultAssetId).collect(Collectors.toSet());
        if (faultAssetIds.size() == 0) return R.ok(stageList);
        List<FaultInfoView> viewList = faultInfoViewService.list(new QueryWrapper<FaultInfoView>()
                .select(FaultInfoView.FAULT_ASSET_ID, FaultInfoView.ASSET_ID)
                .in(FaultInfoView.FAULT_ASSET_ID, faultAssetIds)
        );
        Map<Long, Long> faultAssetMap = viewList.stream().collect(Collectors.toMap(FaultInfoView::getFaultAssetId, FaultInfoView::getAssetId));
        Set<Long> assetIds = viewList.stream().map(FaultInfoView::getAssetId).collect(Collectors.toSet());

        List<AsmsAssetFullInfo> assets = assetFullInfoService.list(new QueryWrapper<AsmsAssetFullInfo>()
                .select(AsmsAssetFullInfo.ASSET_ID, AsmsAssetFullInfo.ASSET_TYPE_NAME)
                .in(AsmsAssetFullInfo.ASSET_ID, assetIds)
        );
        Map<Long, String> assetMap = assets.stream().collect(Collectors.toMap(AsmsAssetFullInfo::getAssetId, AsmsAssetFullInfo::getAssetTypeName));

        stageList.forEach(r -> r.setFaultAssetName(faultAssetMap.get(r.getFaultAssetId()) != null ? assetMap.get(faultAssetMap.get(r.getFaultAssetId())) : ""));

        return R.ok(stageList);
    }

    @ApiOperation("延后处理")
    @PostMapping("/delayResovle")
    public AjaxResult delayResovle(@RequestBody DelayResovleDto dto) {
        String remark = "延后了" + dto.getDelayDays() + "天，延后原因为：" + dto.getDelayReason();
        asmsFaultResolveStageService.update(new UpdateWrapper<AsmsFaultResolveStage>()
                .set(AsmsFaultResolveStage.IS_DELAY_RESOLVE, 0)
                .set(AsmsFaultResolveStage.DELAY_DAY_NUM, dto.getDelayDays())
                .set(AsmsFaultResolveStage.DELAY_REASON, dto.getDelayReason())
                .set(AsmsFaultResolveStage.REMARK, remark)
                .eq(AsmsFaultResolveStage.FAULT_ASSET_ID, dto.getFaultAssetId())
        );
        return AjaxResult.success();
    }

}
